﻿using Appkiz.Apps.Workflow.Library;
using Appkiz.Library.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Tiger.Common;
using Tiger.Models;
using System.Net.Http;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Threading.Tasks;
using System.Net;
using System.Diagnostics;
using System.IO;

namespace Tiger.Controllers
{
    public class RunningController : Controller
    {
        // 流程管理
        private WorkflowMgr wkfMgr = new WorkflowMgr();
        // 数据库上下文
        private WhDbContext whdb = new WhDbContext();
 
        [HttpPost]
        public ActionResult GetPreviewResult(FormCollection collection)
        {
            try
            {
                /*
             * 参数获取
             */
                // 附件ID
                var AttachID = collection["id"];

                /*
                 * 参数校验
                 */
                // 附件ID
                if (string.IsNullOrEmpty(AttachID))
                {
                    return new JsonNetResult(new
                    {
                        Succeed = false,
                        Message = "消息ID不能为空"
                    });
                }
                /*
                 * 调用附件生成服务
                 */
                Attachment attachment = wkfMgr.GetAttachment(AttachID);
                if (attachment == null)
                {
                    return new JsonNetResult(new
                    {
                        Status = -1,
                        Message = "参数错误"
                    });
                }
                else
                {
                    //string filePathName = new WebPage(this.HttpContext.ApplicationInstance.Context).AppDataDir("Att") + attachment.AttID;
                    //filePathName = filePathName.Replace("Tiger", "Workflow");
                    var filePathName = Path.Combine(System.Configuration.ConfigurationManager.AppSettings["AttachFolder"], attachment.AttID);
                    var data = PreparePreviewAsync(AttachID, filePathName);
                    return data;
                }
            }
            catch(Exception e)
            {
                return new JsonNetResult(new
                {
                    Status = -1,
                    Message = e.Message
                });
            }
            
        }

        /// <summary>
        /// 预览Excel
        /// </summary>
        /// <param name="AttachID"></param>
        /// <param name="filePathName"></param>
        /// <returns></returns>
        public ActionResult PreparePreviewAsync(string AttachID, string filePathName)
        {
            try
            {
                // 查询数据库，是否已经生成
                TGR_AttachPreview AttachPreview = whdb.AttachPreview.Where(n => n.AttachID == AttachID).FirstOrDefault();
                if(AttachPreview == null)
                {
                    var data = FilePreviewUtil.PreviewFile(AttachID, filePathName);
                    return (ActionResult)data;
                } else
                {
                    return new JsonNetResult(new
                    {
                        Status = 1,
                        PageCount = AttachPreview.PageCount,
                        PreviewID = AttachPreview.PreviewID
                    });
                }
            }
            catch (WebException ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// CEB文件预览
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public object GetCebPdf(string id)
        {
            try
            {
                /*
                 * 参数校验
                 */
                // 附件ID
                if (string.IsNullOrEmpty(id))
                {
                    return new JsonNetResult(new
                    {
                        Succeed = false,
                        Message = "消息ID不能为空"
                    });
                }
                /*
                 * 调用附件生成服务
                 */
                Attachment attachment = wkfMgr.GetAttachment(id);
                if (attachment == null)
                {
                    return new JsonNetResult(new
                    {
                        Status = -1,
                        Message = "参数错误"
                    });
                }
                else
                {
                    string lower = attachment.AttExtension.ToLower();
                    if (lower == "ceb")
                    {
                        // 查找是否已经存在该文件
                        TGR_AttachPreview AttachPreview = whdb.AttachPreview.Where(n => n.AttachID == id).FirstOrDefault();
                        if (AttachPreview == null)
                        {
                            //string filePathName = new WebPage(this.HttpContext.ApplicationInstance.Context).AppDataDir("Att") + attachment.AttID;
                            //filePathName = filePathName.Replace("Tiger", "Workflow");
                            var filePathName = Path.Combine(System.Configuration.ConfigurationManager.AppSettings["AttachFolder"], attachment.AttID);
                            var data = FilePreviewUtil.PreviewCeb(id, filePathName);
                            return data;
                        }
                        else
                        {
                            return new JsonNetResult(new
                            {
                                Status = 1,
                                PreviewID = AttachPreview.PreviewID
                            });
                        }
                    }
                    else
                    {
                        return new JsonNetResult(new
                        {
                            Status = -1,
                            Message = "类型错误"
                        });
                    }
                }
            }
            catch(Exception e)
            {
                return new JsonNetResult(new
                {
                    Succeed = false,
                    Message = e.Message
                });
            }
        }

        /// <summary>
        /// 获得CEB预览结果
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public object ShowCebResult(string id)
        {
            string PreviewExportFolder = System.Configuration.ConfigurationManager.AppSettings["PreviewExportFolder"];
            return base.File(Path.Combine(PreviewExportFolder, Path.Combine(id, "0.pdf")), "application/pdf");
        }

        /// <summary>
        /// 获取CEB附件预览页面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult GetCebPreview(string id)
        {
            ViewBag.id = id;

            return PartialView("ShowCebPreview");
        }

        /// <summary>
        /// 检测版本
        /// </summary>
        /// <returns></returns>
        public ActionResult CheckVersion()
        {
            // Package
            var name = Request.Params["name"];
            string AppVersion = System.Configuration.ConfigurationManager.AppSettings["AppVersion"];
            string AppUrl = System.Configuration.ConfigurationManager.AppSettings["Appurl"];
            string UpdateNote = System.Configuration.ConfigurationManager.AppSettings["UpdateNote"];

            var dict = new Dictionary<string, object>();
            var dictValue = new
            {
                Name = name,
                Type = "AndroidApp",
                Versions = new List<object>()
                {
                    new
                    {
                        Version = AppVersion,
                        Type = "R",
                        Note = UpdateNote,
                        Url = AppUrl,
                        Dependencies = new { }
                    }
                }
            };
            dict.Add(name, dictValue);

            return new JsonNetResult(dict);
        }
    }
}